<?php

class BooksController extends Controller {
    public $layout = 'contents';
    
    const PAGE_SIZE = 12;
    
    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
//            array('allow',  // allow all users to perform 'list' and 'show' actions
//                'actions' => array(),
//                'users' => array('*'),
//            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array(
                    'index', 'create', 'update', 'changeStatus', 'changeRecommend',
                    'changePicking', 'view', 'viewChapterContents', 'addChapterContent'
                ),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'batchProcess'),
                'users' => array('admin'),
            ),
            array('deny',  // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate() {
        $model = new Book;
        $model->node_id = Yii::app()->request->getParam('node');
        if (isset($_POST['Book'])) {
            $model->attributes = $_POST['Book'];
            if($model->save()) {
                $this->redirect(array('index', 'node' => $_POST['Book']['node_id']));
            }
        }
        $this->render('edit', array('model' => $model));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate() {
        $model = $this->loadModel();
        if (isset($_POST['Book'])) {
            $model->attributes = $_POST['Book'];
            if ($model->save()) {
                $this->redirect(array('index', 'node' => $_POST['Book']['node_id']));
            }
        }
        $this->render('edit', array('model' => $model));
    }

    // 查看书籍章节内容
    public function actionView() {
        $book = $this->loadModel();
        $book_id = Yii::app()->request->getParam("bid");
        $cid = Yii::app()->request->getParam('category', 0);
        $chapter_trees = BookChapterCategory::model()->getCTreeViewDatas($book_id, 0, 'view');

        $category = BookChapterCategory::model()->find("id = {$cid}");
//        $category = BookChapterCategory::model()->find("book_id = {$book->id} AND id = {$bid}");
        if ($category === null) {
            $category = $this->newChapterCategory($book);
        } else {
            $category = $this->updateCategory($book, $cid);
        }

        $this->render('view', array(
            'book' => $book,
            'chapter_trees' => $chapter_trees,
            'category' => $category,
        ));
    }

    // 增加书籍章节分类
    protected function newChapterCategory($book) {
        $category = new BookChapterCategory();
        $category->author = $book->author;
        if (isset($_POST['BookChapterCategory'])) {
            $category->attributes = $_POST['BookChapterCategory'];
            if ($book->addChapterCategory($category)) {
//                Book::model()->updateCounters(array('pictures_count' => 1), "id = {$book->id}");
                Yii::app()->user->setFlash('add_chapter_category_success', Yii::t('book', 'add_chapter_category_success'));
                $this->refresh();
            }
        }
        return $category;
    }

    // 更新书籍章节分类
    protected function updateCategory($book, $chapter_category_id) {
        $category = BookChapterCategory::model()->find("book_id = {$book->id} AND id = {$chapter_category_id}");
        if (isset($_POST['BookChapterCategory'])) {
            $category->attributes = $_POST['BookChapterCategory'];
            if ($book->addChapterCategory($category)) {
                Yii::app()->user->setFlash('update_chapter_category_success', Yii::t('book', 'update_chapter_category_success'));
                $this->refresh();
            }
        }
        return $category;
    }

    // 查看书籍章节内容
    public function actionViewChapterContents() {
        $book = $this->loadModel();
        $book_id = Yii::app()->request->getParam("bid");
        $cid = Yii::app()->request->getParam('category', 0);
        $content_id = Yii::app()->request->getParam('content_id', 0);

        $chapter_trees = BookChapterCategory::model()->getCTreeViewDatas($book_id, 0, 'viewChapterContents');
        $chapter_contents = BookChapterContent::model()->findAll("category_id = {$cid}");
        $content = BookChapterContent::model()->findByPk($content_id);
        if ($content === null) {
            $content = $this->newChapterContent($content);
        } else {
            $content = $this->updateChapterContent($content, $cid);
        }

        $this->render('viewChapterContents', array(
            'book' => $book,
            'chapter_trees' => $chapter_trees,
            'chapter_contents' => $chapter_contents,
            'content' => $content,
        ));
    }

    // 增加书籍章节内容
    protected function newChapterContent($content) {
        $content = new BookChapterContent();
        if (isset($_POST['BookChapterContent'])) {
            $content->attributes = $_POST['BookChapterContent'];
            if ($content->save()) {
                Yii::app()->user->setFlash('add_chapter_content_success', Yii::t('book', 'add_chapter_content_success'));
                $this->refresh();
            }
//            if ($content->addChapterContent($content)) {
////                Book::model()->updateCounters(array('pictures_count' => 1), "id = {$book->id}");
//                Yii::app()->user->setFlash('add_picture_success', Yii::t('album', 'add_picture_success'));
//                $this->refresh();
//            }
        }
        return $content;
    }

    // 更新书籍章节内容
    protected function updateChapterContent($chapter_content, $chapter_category_id) {
        $chapter_content = BookChapterContent::model()->find("id = {$chapter_content->id}");
        if (isset($_POST['BookChapterContent'])) {
            $chapter_content->attributes = $_POST['BookChapterContent'];
            if ($chapter_content->save()) {
                Yii::app()->user->setFlash('update_chapter_content_success', Yii::t('book', 'update_chapter_content_success'));
                $this->refresh();
            }
//            if ($chapter_content->addChapterContent($category)) {
//                Yii::app()->user->setFlash('update_picture_success', Yii::t('album', 'update_picture_success'));
//                $this->refresh();
//            }
        }
        return $chapter_content;
    }

    // change status
    function actionChangeStatus() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Book::model()->findByPk($id);
            switch ($model->status) {
                case Options::STATUS_DRAFT:
                    $status = Options::STATUS_PUBLISHED;
                    break;
                case Options::STATUS_PUBLISHED:
                    $status = Options::STATUS_DRAFT;
                    break;
            }
            $model->status = $status;
            try {
                $model->save(false);
//                print_r($model->getErrors());
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->statusIconFormat;
        }
    }

    /**
     * change "is_recommend" value, false or true
     */
    public function actionChangeRecommend() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Book::model()->findByPk($id);
            $value = (intval($model->is_recommend))
                ? Options::RECOMMEND_NO
                : Options::RECOMMEND_YES;
            $model->is_recommend = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isRecommendIconFormat;
        }
    }

    /*
     * change "is_picking" value, false or true
     */
    public function actionChangePicking() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Book::model()->findByPk($id);
            $value = (intval($model->is_picking))
                ? Options::PICKING_NO
                : Options::PICKING_YES;
            $model->is_picking = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isPickingIconFormat;
        }
    }

    // 批量更新
    public function actionBatchProcess() {
        if (Yii::app()->request->isPostRequest) {
            $action = strtolower(trim(Yii::app()->request->getPost('action_list')));
            switch ($action) {
                case 'update_order_pos':
                    $order_pos = Yii::app()->request->getPost('order_pos');
                    if (!empty($order_pos)) {
                        foreach ($order_pos as $key => $value) {
                            Book::model()->updateByPk($key, array('order_pos' => $value));
                        }
                    }
                    break;
                case 'delete_selected':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Book::model()->findByPk($id)->delete();
                        }
                    }
                    break;
                case 'move_to_recycle_bin':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Book::model()->updateByPk($id, array(
                                'status' => Options::STATUS_PENDING_DELETE));
                        }
                    }
                    break;
            }

            $this->redirect(array('index', 'node' => Yii::app()->request->getPost('current_node')));
        } else {
            throw new CHttpException(400, Yii::t('common', 'invalid_request'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $current_node = Yii::app()->request->getParam('node');
        $criteria = new CDbCriteria;
        $criteria->condition = 'status != ' . Options::STATUS_PENDING_DELETE;
        if (intval($current_node)) {
            $criteria->addCondition("node_id = {$current_node}");
        }

        $pages = new CPagination(Book::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort = new CSort('Book');
        $sort->applyOrder($criteria);

        $models = Book::model()->findAll($criteria);

        $this->render('index', array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'current_node' => $current_node,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadModel() {
        if($this->_model === null) {
            if (isset($_GET['bid']))
                $this->_model = Book::model()->findbyPk($_GET['bid']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }
    
}
